#include "MeshAdjacency.hpp"

#include <iostream>

#include "Algorithm.hpp"

MeshAdjacency::MeshAdjacency(Mesh aMesh,
                             int   aMaxFaces)
:  mMaxFaces(aMaxFaces)
{
   Rebuild(aMesh);
}

void MeshAdjacency::Rebuild(const Mesh& aMesh)
{
   mMesh.ref(aMesh);
   std::cerr << "MeshAdjacency::Rebuild()";
   mEdgeBuilt=true;
   mEdgeData.clear();
   mVertexData.assign(mMesh.verts.size() * mMaxFaces, -1);

   for (size_t i = 0; i < mMesh.faces.size(); ++i)
   {
      const Face& f = mMesh.faces[i];
      InsertLink(i, f.vertex[0]);
      InsertLink(i, f.vertex[1]);
      InsertLink(i, f.vertex[2]);
   }
   BuildEdgeAdjacency();
   std::cerr << ".\n";
}

void MeshAdjacency::BuildEdgeAdjacency()
{
   for (size_t i = 0; i < mMesh.verts.size(); ++i)
   {
      int faces[128];
      int fcount = GetVertexFaces(i, faces);
      for (size_t j = 0; j < fcount; ++j)
      {
         int fi = faces[j];
         Face& f = mMesh.faces[fi];
         if (f.vertex[0] > i)
         {
            mEdgeData[Edge(i, f.vertex[0])].push_back(fi);
         }
      }
   }
}

void MeshAdjacency::GetVertexAdjacentFaces(const IndexList& aVertices,
                                           IndexList&       aAdjacentFaces)
{
   
   for (size_t i = 0; i < aVertices.size(); ++i)
   {
      int faces[128];
      int fCount = GetVertexFaces(aVertices[i], faces);
      aAdjacentFaces.insert(aAdjacentFaces.end(), faces, faces + fCount);
   }
   Algorithm::make_unique(aAdjacentFaces);
}
